package com.jadesoft.common.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;


public class RequestContextFilter implements Filter {
	private static final MultipartResolver multipartResolver = new CommonsMultipartResolver();
	private ServletContext ctx;
	private static Logger logger = Logger.getLogger(RequestContextFilter.class);

	public void destroy() {
		RequestContext.set(null);
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		boolean isMultipart = multipartResolver
				.isMultipart((HttpServletRequest) request);
		if (isMultipart) {
			request = multipartResolver
					.resolveMultipart((HttpServletRequest) request);
		}

		RequestContext.set(new RequestContext((HttpServletRequest) request,
				(HttpServletResponse) response, ctx, isMultipart));

		try {
			dumpRequest((HttpServletRequest) request);
			chain.doFilter(request, response);
		} finally {
			RequestContext.set(null);
		}
	}

	public void init(FilterConfig cfg) throws ServletException {
		ctx = cfg.getServletContext();
	}

	// Helper Method to dump the request, will be useful for testing ajax
	// request in IE
	private void dumpRequest(HttpServletRequest request) {
		String query = request.getQueryString();
		logger.info(request.getRequestURL()+ (query == null ? "" : "?" + query));
	}
}
